package main

import (
	"context"
	_ "dingusxp/trial/guestbook/internal/store"
	"dingusxp/trial/guestbook/server"
	"dingusxp/trial/guestbook/store/factory"
	"flag"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"
)

var port = flag.String("port", "8080", "set server bind port")
var showHelp = flag.Bool("h", false, "show usage")

func main() {

	flag.Parse()
	if *showHelp {
		flag.PrintDefaults()
		return
	}

	store, err := factory.New("mem")
	if err != nil {
		panic("init store failed: " + err.Error())
	}

	addr := strings.Join([]string{":", *port}, "") // :8080
	gs, err := server.NewGuestbookServer(addr, store)
	if err != nil {
		panic("init guestbook server failed: " + err.Error())
	}

	errChan, err := gs.ListenAndServe()
	if err != nil {
		log.Printf("server start failed: %s\n", err.Error())
		return
	}
	log.Printf("server starts and listening %s ...\n", addr)

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)

	select {
	case err = <-errChan:
		log.Printf("server start failed: %s \n", err)
		return
	case <-c:
		log.Printf("server will shutdown...\n")
		ctx, cf := context.WithTimeout(context.Background(), time.Second)
		defer cf()
		err = gs.Shutdown(ctx)
	}

	if err != nil {
		log.Printf("server shutdown failed: %s \n", err.Error())
		return
	}
	log.Printf("server shundown succeed\n")
}
